In this article I will show you to pass parameter to an angularJS controller using angularJS method ng-init. If the user passes the value via ng-init into an html page and you will get the parameter from the scope object of angularJS controller.
MVC View:
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.5/angular.js"></script>
<script src="~/Scripts/app.js"></script>
<div data-ng-app="myModule">
<div data-ng-controller="myController" data-ng-init="init(@Model.UserId)">
<h2>Name of the employee is {{name}}</h2>
</div>
</div>
AngularJS app.js:
angular.module('myModule', []);
function myController($compile, $scope, $http) {
//Thisfunction is sort of private constructor for controller
$scope.init = function (id) {
$scope.myInterval = 5000;
$scope.name = null;
$scope.UserId = id;
$http({
method: 'Get',
url: '/Home/GetData',
params: {
UserId: $scope.UserId
},
}).success(function (data, status,headers, config) {
$scope.name = data;
}).error(function (data, status, headers, config) {
$scope.message = 'Unexpected Error';
});
}
MVC Controller:
public JsonResult GetData(int UserId)
{
using (models context = new models())
{
var ret = context.Users.Where(s => s.UserId == UserId).ToList().Select(x=> new { x.UserId,x.Name }).ToList();
return Json(ret, JsonRequestBehavior.AllowGet);
}
}
The MVC controller receives the parameter UserId and filters the record from the Collection (Users) and return as JSON string and bind to the html element.
Output:
Post your comments / questions
Recent Article
- How to create custom 404 error page in Django?
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
Related Article